package P150;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author LiangMu
 * @version \$Id: P19.java, v 0.1, 2024年07月04日 19:40 LiangMu Exp $$
 */
public class P19 {
    public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 1) {
            return strs[0];
        }
        StringBuilder builder = new StringBuilder();
        List<String> args = Arrays.asList(strs);
        args.sort(Comparator.comparing(String::length));
        String start = args.get(0);
        char[] chars = start.toCharArray();
        for (char aChar : chars) {
            String temp = builder.toString() + aChar;
            for (String arg : args) {
                if (!arg.startsWith(temp)) {
                    return builder.toString();
                }
            }
            builder.append(aChar);
        }
        return builder.toString();
    }
}
